package org.example.controller;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.example.Contant.BusinessException;
import org.example.Contant.Result;
import org.example.dto.ResumeAnalysisResponse;
import org.example.dto.UserDto;
import org.example.service.AIService;
import org.example.service.ResumeAnalysisService;
import org.example.service.ResumeService;
import org.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/resume")
public class ResumeController {

    private final ResumeAnalysisService resumeAnalysisService;

    @Resource
    private RedisTemplate<String, UserDto> redisTemplate;

    @Autowired
    private ResumeService resumeService;

    @Autowired
    private AIService aiService;

    @Autowired
    public ResumeController(ResumeAnalysisService resumeAnalysisService) {
        this.resumeAnalysisService = resumeAnalysisService;
    }



    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<ResumeAnalysisResponse> uploadResume(
        @RequestParam(value = "file",required = false) MultipartFile file,
        @RequestParam(value = "additionalInfo", required = false) String additionalInfo,
        HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if ("".equals(token)){
            throw new BusinessException("500","token失效");
        }
        String username = JwtUtil.parseToken(token);
        UserDto userDto = redisTemplate.opsForValue().get(username);
        int userId = userDto.getId();
        try {
            // 验证文件是否为空
            if (file.isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(new ResumeAnalysisResponse(false, "未选择文件", null));
            }
            // 验证文件大小（最大5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return ResponseEntity.badRequest()
                        .body(new ResumeAnalysisResponse(false, "文件大小超过5MB限制", null));
            }
            // 处理简历分析
            ResumeAnalysisResponse response = resumeAnalysisService.analyzeResumeFile(file, additionalInfo,userId);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.internalServerError()
                    .body(new ResumeAnalysisResponse(false, "服务器错误: " + e.getMessage(), null));
        }
    }

//    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
//    public Result<String> uploadResume(
//        @RequestParam(value = "file", required = false) MultipartFile file,
//        @RequestParam(value = "additionalInfo", required = false) String additionalInfo,
//        HttpServletRequest request) {
//        int userId = getUserIdByToken(request);
//        // 处理简历分析
//        String response = resumeAnalysisService.analyzeResumeFile(file, additionalInfo, userId);
//        //表示已经给ai发送过简历了
//        flag = 1;
//        return Result.success("200", response);
//    }

    @PostMapping("/ask")
    public Result<String> askAiQuestion(@RequestParam String question,HttpServletRequest request){
        int userId= getUserIdByToken(request);
        //根据userId获取最新的简历
        String info = resumeService.getInfoByUserIdNew(userId);
        //将用户简历和用户的提问拼成一个问题
        String fullQuestion = resumeAnalysisService.createFullQuestion(question, info);
        //调用ai接口
        String answer = aiService.callAIApi(fullQuestion);
        System.out.println("ai的回答"+answer);
        return Result.success("200",answer);
    }

    /**
     * 通过token获取userId
     * @param request
     * @return
     */
    private int getUserIdByToken(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        if ("".equals(token)) {
            throw new BusinessException("500", "token失效");
        }
        String username = JwtUtil.parseToken(token);
        UserDto userDto = redisTemplate.opsForValue().get(username);
        return userDto.getId();
    }
}
